import React, { Component } from 'react';
import Taro, { Config } from '@tarojs/taro';
import { View, Input, ScrollView } from '@tarojs/components'
import { connect } from 'react-redux'
import { initLocation, customStatus, setOpenLocation } from '@/store/location/action'
import { debounce } from '@/utils'
import classnames from 'classnames'
import Iconfont from '@/components/Iconfont'
import map from '@/utils/map'
import { AtButton } from 'taro-ui'
import './index.scss'

interface State {
    address: any
    pois: any
    loadLocation: boolean
    searchPois: any
    keyword: string
    isOpenLocation: any
}

@connect<any>(({ location }) => ({ location }), _dispatch => ({
    dispatchLocation(params) {
        return _dispatch(initLocation(params))
    },
    dispatchCustomStutas(status) {
        return _dispatch(customStatus(status))
    },
    dispatchOpenLocation(status) {
        return _dispatch(setOpenLocation(status))
    }
}))
export default class Index extends Component<any, State> {
    constructor() {
        super(...arguments)
        this.state = {
            address: null,
            pois: null,
            loadLocation: false,
            searchPois: null,
            keyword: '',
            // eslint-disable-next-line taro/duplicate-name-of-state-and-props
            isOpenLocation: this.props.location.isOpenLocation
        }
    }
    state: State
    UNSAFE_componentWillMount() { }
    componentDidMount() {
        const { address } = this.props.location
        let params
        if (address) {
            const { lat: latitude, lng: longitude } = address.location
            params = {
                location: { latitude, longitude }
            }
        }

        this.getLocation(params)
    }
    UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
        const { location } = nextProps
        if (location) {
            if (!this.state.isOpenLocation) {
                if (location.isOpenLocation) {
                    this.setState({
                        isOpenLocation: location.isOpenLocation
                    })
                }
            }
        }
    }
    componentWillUnmount() { }
    componentDidShow() { }
    componentDidHide() { }
    componentDidCatchError() { }
    componentDidNotFound() { }
    // 当前位置信息
    async getLocation(params?) {
        const reverseGeocoder: any = await map.reverseGeocoder(params)
        // const { dispatchOpenLocation } = this.props
        if (reverseGeocoder) {
            let address
            if (params) {
                address = this.props.location.address
            } else {
                const { dispatchLocation } = this.props
                address = {
                    city: reverseGeocoder.ad_info.city,
                    address: reverseGeocoder.address,
                    location: reverseGeocoder.location,
                    title: reverseGeocoder.formatted_addresses.recommend
                }
                dispatchLocation(address)
            }
            const pois = reverseGeocoder.pois
            this.setState({
                address,
                pois,
                loadLocation: true
            })
        } else {
            this.setState({
                loadLocation: true
            })
        }
    }

    // 开启定位
    openSetting() {
        Taro.openSetting().then(res => {
            const status = res.authSetting['scope.userLocation']
            if (status) {
                const { dispatchCustomStutas, dispatchOpenLocation } = this.props
                this.setState({
                    loadLocation: false
                })
                dispatchOpenLocation(true)
                dispatchCustomStutas(false)
                this.getLocation()
            }
        })
    }

    // 城市列表
    toCityList() {
        Taro.navigateTo({
            url: '/pages/store/city/index'
        })
    }

    // 重新定位
    reGetLocation = debounce(() => {
        this.setState({
            loadLocation: false
        }, () => this.getLocation().then(() => {
            const { dispatchCustomStutas } = this.props
            dispatchCustomStutas(false)
            Taro.navigateBack()
        }))
    }, 100)

    // 切换地址
    switchAddress(pois) {
        const { dispatchLocation, dispatchCustomStutas } = this.props
        const address = {
            city: pois.ad_info.city,
            address: pois.address,
            location: pois.location,
            title: pois.title
        }
        // console.log(location)
        dispatchCustomStutas(address)
        dispatchLocation(address)
        this.setState({
            address
        }, () => Taro.navigateBack())
    }

    // 搜索地址
    searchLocation = debounce((e) => {
        const { value: keyword } = e.detail
        const { cityName } = this.props.location
        let params = {
            keyword,
            region: cityName
        }

        if (keyword) {
            map.search(params).then((pois: any) => {
                this.setState({
                    searchPois: pois.map(v => {
                        const title = v.title.replace(new RegExp(keyword), (m, s1) => {
                            return `|${m}|`
                        }).split('|')
                        return {
                            ...v,
                            title
                        }
                    })
                })
            })
        } else {
            this.setState({
                searchPois: null
            })
        }
        this.setState({
            keyword
        })
    }, 400)

    setLocation(pois, e) {
        const { dispatchLocation, dispatchCustomStutas } = this.props
        const address = {
            city: pois.city,
            address: pois.address,
            location: pois.location,
            title: pois.title.join('')
        }
        dispatchCustomStutas(address)
        dispatchLocation(address).then(res => {
            const { lat: latitude, lng: longitude } = address.location
            const params = {
                location: { latitude, longitude }
            }
            this.getLocation(params)
            this.setState({
                keyword: ''
            }, () => Taro.navigateBack())
        })
    }
    // 搜索地址视图
    searchAddressView() {
        const { searchPois, keyword } = this.state
        return searchPois && (
            <ScrollView scroll-y className='search-address'>
                {
                    searchPois.map(pois => {
                        return (
                            <View onClick={(e) => this.setLocation(pois, e)} key={pois.id} className='address-list'>
                                <View className='name'>
                                    <View className='span'>
                                        {
                                            pois.title.map((t, tidx) => {
                                                return t !== keyword ? t : <View key={tidx + keyword} className='strong'>{t}</View>
                                            })
                                        }
                                    </View>
                                    {
                                        pois._distance && <View className='em'>{(pois._distance / 1000).toFixed(1)}千米</View>
                                    }
                                </View>
                                <View className='address'>{pois.address}</View>
                            </View>
                        )
                    })
                }
            </ScrollView>
        )
    }

    render() {
        const { address, loadLocation, pois, keyword, isOpenLocation } = this.state
        const { cityName } = this.props.location
        return (
            <View className={classnames('region', keyword.length && 'show-search')}>
                <View className='city-info'>
                    <View className='option-city' onClick={() => this.toCityList()}>
                        <Iconfont size='44' color='#12B3FF' name='icon-Rectangle' />
                        {
                            cityName ? <View className='city-name'>{cityName}</View> :
                                (address ? <View className='city-name'>{address.city || '定位中'}</View> : <View className='city-name'>获取位置失败</View>)
                        }
                        <Iconfont size='26' color='#CCCCCC' name='icon-shaixuanxialajiantou' />
                    </View>
                    <View className='import-keywords'><Input onInput={(e) => this.searchLocation(e)} placeholderStyle='text-align:center;color: #999999;font-size: 26rpx' className='ipt' placeholder='输入地址、写字楼、小区'></Input></View>
                </View>
                <ScrollView className='info-wrap' scroll-y>
                    <View>
                        <View className='sub-title'>当前位置</View>
                        {
                            address ?
                                <View className='current-location'>
                                    <View className='location-info'>
                                        <View className='name'>{address.title}</View>
                                        <View className='address'>{address.address}</View>
                                    </View>
                                    {
                                        isOpenLocation ?
                                            (<AtButton onClick={(e) => this.reGetLocation(e)} className='reset-location' size='small' loading={!loadLocation} type='secondary'>
                                                {!loadLocation ? '' : '重新定位'}
                                            </AtButton>) :
                                            (<AtButton className='reset-location' onClick={() => this.openSetting()} size='small' loading={!loadLocation} type='secondary'>
                                                {!loadLocation ? '' : '开启定位'}
                                            </AtButton>)
                                    }
                                </View> :
                                <View className='current-location'>
                                    <View className='location-info'><View className='name'>暂无位置信息</View></View>
                                    <AtButton className='reset-location' onClick={() => this.openSetting()} size='small' loading={!loadLocation} type='secondary'>
                                        {!loadLocation ? '' : '开启定位'}
                                    </AtButton>
                                </View>
                        }
                        {
                            pois && (<View className='range-wrap'>
                                <View className='sub-title'>附近地址</View>
                                <View className='range-address'>
                                    {
                                        pois.map(v => {
                                            return (
                                                <View key={v.id} onClick={(e) => this.switchAddress(v, e)} className='address-list'>
                                                    <View className='name'>{v.title}</View>
                                                    <View className='address'>{v.address}</View>
                                                </View>
                                            )
                                        })
                                    }
                                </View>
                            </View>)
                        }
                    </View>
                </ScrollView>
                {this.searchAddressView()}
            </View>
        )
    }
}
